package com.agile.leetcode.easy.bigNumCalculate;

/**
 * 大数相乘
 *
 * @Author:ChenZhangKun
 * @Date: 2021/5/9 22:32
 */
public class BigNumMultiply {
    public static void main(String[] args) {
        BigNumMultiply multiply = new BigNumMultiply();
        String num1 = "10";
        String num2 = "99";
        String s = multiply.bigNumMultiply(num1, num2);
        System.out.println(s);
    }

    public String bigNumMultiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }
        // 拿到字符数组
        char[] charNum1 = num1.toCharArray();
        char[] charNum2 = num2.toCharArray();
        // 创建数组
        int[] value = new int[num1.length() + num2.length()];
        for (int i = charNum1.length - 1; i >= 0; i--) {
            for (int j = charNum2.length - 1; j >= 0; j--) {
                int index = charNum1.length - 1 - i + charNum2.length - 1 - j;
                // 相乘
                value[index] += (charNum1[i] - '0') * (charNum2[j] - '0');
            }
        }
        // 进位
        for (int i = 0; i < value.length - 1; i++) {
            // 进位
            value[i + 1] += value[i] / 10;
            // 取余
            value[i] = value[i] % 10;
        }
        int index = value.length - 1;
        // 取出0位
        while (value[index] == 0) {
            index--;
        }
        StringBuilder builder = new StringBuilder();
        while (index >= 0) {
            builder.append(value[index--]);
        }
        return builder.toString();
    }
}
